layui.use(['jquery', 'element', 'layer', 'form', 'table', 'util', 'configs', 'template', 'echarts', 'cookie','formSelects'], function () {
    var $ = layui.jquery,
        element = layui.element,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        util = layui.util,
        template = layui.template,
        echarts = layui.echarts,
        config = layui.configs,
        cookie = layui.cookie,
        formSelects = layui.formSelects;
    var areaId = null;
    var moIds = null;
    var mo_cookie = $.cookie("this_motor");
    var this_motor = null;
    if (mo_cookie != null && mo_cookie != "" && mo_cookie != undefined) {
        this_motor = JSON.parse(mo_cookie);
    }
    var ctype = null;
    var dataTypeArr = [];
    var timer = null;
    var flag = 0;
    //amplitudeChart(振幅波形图)、displacementChart(位移波形图)、originalChart(原始折线图)
    var amplitudeChart = echarts.init(document.getElementById("amplitude"),"dark");
    var displacementChart = echarts.init(document.getElementById("displacement"),"dark");
    var originalChart = echarts.init(document.getElementById("original"),"dark");
    var amplitudeOption = {} , displacementOption = {} , originalOption = {};
    // var colors = ['#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#97b552','#07a2a4'];
    var colors = ['#ac3ff2','#ff6c00','#EAEA26', '#34da62','#3cefff','#FE5656'];

    initAll();
    function initAll() {
        dataType();
        getArea();
    }

    //计算列表高度
    function rockDataListHeight(){
        var mh = $('.mainbody').height();
        var toph = $('.left-part .layui-card-top').height();
        $('.left-part .layui-card-bottom').height(mh - toph - 60);
    };
    window.onresize = function () {
        rockDataListHeight();
        amplitudeChart.resize();
        displacementChart.resize();
        originalChart.resize();
    };
    //是否显示振幅、位移、加速度
    function dataType() {
        var motorConf = config.motorConf;
        var options = "";
        for (var k in motorConf) {
            if (motorConf[k].isShow) {
                dataTypeArr.push(motorConf[k].text);
                options += '<option value="' + motorConf[k].text + '">' + motorConf[k].text + '</option>'
            }
        }
        $('select[name="dataType"]').append(options);
        form.render('select');
        ctype = $('select[name="dataType"] option:selected').val();
        if (dataTypeArr.length > 1) { //如果只有一种，则不显示该选择框
            $(".dataTypeWrap").removeClass("layui-hide");
        }
        //监听振幅、位移、加速度选择
        form.on('select(dataType)', function (data) {
            ctype = data.value;
        });
    }

    //监听区域选择
    form.on('select(areaMenu)', function (data) {
        flag = 1;
        $.removeCookie("this_motor");
        this_motor = null;
        $("#troughMenu").html("");
        $(".multi-motors").html("");
        formSelects.render('select-motor');
        areaId = data.value;
        getTrough(areaId);
    });
    //监听槽位选择
    form.on('select(troughMenu)', function (data) {
        flag = 1;
        $.removeCookie("this_motor");
        this_motor = null;
        $(".multi-motors").html("");
        formSelects.render('select-motor');
        var troughId = data.value;
        getMotors(troughId);
    });
    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    $("#areaMenu").html(template("motor-areas-tpl", result));
                    if (this_motor != null) {
                        form.val('parameter', {
                            "areaMenu": this_motor.areaId
                        });
                    } else {
                        if(result.data != null && result.data.length >0){
                            if(flag == 0){
                                form.val('parameter', {
                                    "areaMenu": result.data[0].areaId
                                })
                            }
                        }
                    }
                    form.render('select');
                    areaId = $("#areaMenu option:checked").val();
                    // 按区域查槽位
                    getTrough(areaId);

                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //按区域查槽位
    function getTrough(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_trough/selectAreaTrough/v1.0",
            type: "post",
            datatype: "json",
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $("#troughMenu").html(template("motor-trough-tpl", result));
                    if (this_motor != null && this_motor != undefined) {
                        form.val('parameter', {
                            "troughMenu": this_motor.troughId
                        });
                        form.render('select');
                        var troughId = $("#troughMenu option:checked").val();
                        // 按槽位查马达
                        getMotors(troughId);
                    } else {
                        if(result.data != null && result.data.length >0){
                            if(flag == 0){
                                form.val('parameter', {
                                    "troughMenu": result.data[0].troughId
                                });
                                form.render('select');
                                var troughId = $("#troughMenu option:checked").val();
                                // 按槽位查马达
                                getMotors(troughId);
                            }else{
                                form.render('select');
                            }
                        }else{
                            form.render('select');
                            formSelects.render('select-motor');
                            $('[lay-id="motor-info"]').remove();
                            // myChart.clear();
                            clearInterval(timer);
                            // blankChart();
                        }
                    }

                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    // 按槽位查马达
    function getMotors(troughId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            data: {
                troughId: troughId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".multi-motors").html(template("motors-tpl", result));
                    formSelects.render('select-motor');
                    formSelects.btns('select-motor', []);
                    if (this_motor != null) {
                        formSelects.value('select-motor', [this_motor.moId],true);
                        $(".searchBtn").click();
                    }else{
                        if(result.data != null && result.data.length >0){
                            if(flag == 0){
                                formSelects.value('select-motor', [result.data[0].moId],true);
                                $(".searchBtn").click();
                            }
                        }
                    }

                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //查询
    $(".searchBtn").click(function () {
        clearInterval(timer);
        $.removeCookie("this_motor");
        this_motor = null;
        moIds = formSelects.value('select-motor', 'valStr');
        // console.log("formSelects: id="+moIds);
        if(moIds == ""){
            layer.alert("请选择马达");
            blankChart();
            $(".tableBody").html('');
        }else{
            getChartData(moIds);
        }
        return false;
    });

    //加载设备信息
    function getChartData(moIds) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_latest_rec/select/v1.0",
            type: "post",
            data: {
                moIds: moIds
            },
            dataType: "json",
            beforeSend: function () {
                clearInterval(timer);
                isShowLoading(1); // 1 显示
            },
            success: function (result) {
                // console.log("getChartData: id="+moIds);
                if (result.stateCode == 0) {
                    if (result.data != null) { //list有值
                        clearEc();
                        bindAllDatas(result);
                        isShowLoading(0); // 0隐藏
                    }
                } else {
                    layer.alert(result.stateMsg);
                    blankChart();
                }
            },
            complete: function () {
                isShowLoading(0);
                timer = setInterval(function () {
                    refresh(moIds);
                }, config.motorInter);
            }
        });
    }

    //左下表格
    function bindRockDataTable(result) {
        var resArr = [];
        var sourceArr = [];
        for(var k in result){
            if(result[k].length >0){
                if(result[k][0].moName != null){
                    resArr.push({moName:result[k][0].moName,dataList:result[k]});
                }else{
                    resArr.push({moName:'',dataList:result[k]});
                }
            }

        }
        for(var i=0;i<resArr.length;i++){
            var dataList = resArr[i].dataList;
            if(dataList != null && dataList.length > 0){
                for(var j=0;j<dataList.length;j++){
                    var sourceObj = {};
                    if(dataList[j].moName != null){
                        sourceObj["moName"] = dataList[j].moName;
                    }else{
                        sourceObj["moName"] = "";
                    }
                    sourceObj["strRecTime"] = dataList[j].strRecTime;
                    sourceObj["shockData"] = dataList[j].shockData;
                    sourceObj["displacementData"] = dataList[j].displacementData;
                    sourceObj["sort"] = (dataList[j].recTime +''+ dataList[j].moId)-0;
                    sourceArr.unshift(sourceObj);
                }
            }
        }
        sourceArr = sourceArr.sort(initSort("sort","desc"));
        var obj = {list:sourceArr};
        $(".tableBody").html(template("rockDataList-tpl",obj));
        rockDataListHeight();
    }

    //振幅阶梯线图
    // var color = [];
    var chartTitle = "";
    function AmplitudeStepLine(obj) {
        var optionSeries = [];
        if (obj.counts == 1) { //单个
            chartTitle = obj.moName[0] + obj.ctype + "实时图";
            //color = ["#1e9fff", "red", "#fcce10", "red", "#fcce10"];
            isShowLegend = true;
            optionSeries = [{
                //实时数据
                name: obj.ctype,
                type: 'line',
                step: 'middle',
                symbol: 'none',
                data: obj.singleObj.shockData
            },
                {
                name: '上限',
                type: 'line',
                data: obj.singleObj.upperLimit,
                symbolSize: 0,
                itemStyle : {
                    normal : {
                        color:'red',
                        lineStyle:{
                            color:'red',
                            type: 'dashed',
                            width: 2
                        }
                    }
                },
            }, {
                name: '管制上限',
                type: 'line',
                data: obj.singleObj.upperLimitInner,
                symbolSize: 0,
                    itemStyle : {
                        normal : {
                            color:'#fcce10',
                            lineStyle:{
                                color:'#fcce10',
                                type: 'dashed',
                                width: 2
                            }
                        }
                    },
            },
                {
                name: '下限',
                type: 'line',
                data: obj.singleObj.lowerLimit,
                symbolSize: 0,
                    itemStyle : {
                        normal : {
                            color:'red',
                            lineStyle:{
                                color:'red',
                                type: 'dashed',
                                width: 2
                            }
                        }
                    },
            }, {
                name: '管制下限',
                type: 'line',
                data: obj.singleObj.lowerLimitInner,
                symbolSize: 0,
                    itemStyle : {
                        normal : {
                            color:'#fcce10',
                            lineStyle:{
                                color:'#fcce10',
                                type: 'dashed',
                                width: 2
                            }
                        }
                    },
            }
            ];
            for(let i=0;i<optionSeries.length;i++){
                var _lenged = [];
                _lenged = Array.from(new Set(optionSeries[i].data));
                if( !(_lenged.length == 1 && _lenged[0] == null) ){
                    obj.legend.push(optionSeries[i].name);
                }
            }
        } else if (obj.counts == 0) {  //多马达
            chartTitle = obj.ctype + "实时图";
            // color = colors;
            isShowLegend = true;
            obj.legend = obj.moName;
            for (var i = 0; i < obj.multiArr.length; i++) {
                optionSeries.push({
                    name: obj.multiArr[i].name,
                    type: 'line',
                    step: 'middle',
                    symbol: 'none',
                    data: obj.multiArr[i].value
                });
            }
        }
        var element = {
            title: chartTitle,
            unit: 'mm/s',
            max: 200,
            isShowLegend: isShowLegend,
            isShowAxisLabel: true
        };
        amplitudeOption = initOptions(obj,element,optionSeries);
        amplitudeOption.legend.data = obj.legend;
        amplitudeOption.xAxis.name = '时间';
        amplitudeChart.setOption(amplitudeOption);
    }

    //原始折线图
    function originalLineChart(obj) {
        var optionSeries = [];
        for (var i = 0; i < obj.multiArr.length; i++) {
            optionSeries.push({
                //实时数据
                name: obj.multiArr[i].name,
                type: 'line',
                symbol: 'none',
                data: obj.multiArr[i].value
            });
        }
        var element = {
            title: '大数据实时图',
            unit: 'mm/s',
            max: 200,
            isShowLegend: false,
            isShowAxisLabel: false
        };
        originalOption = initOptions(obj,element,optionSeries);
        originalChart.setOption(originalOption);
    }
    //空白图
    function blankChart(){
        clearInterval(timer);
        clearEc();
        amplitudeOption = {xAxis: {},yAxis: {}};
        displacementOption = {xAxis: {},yAxis: {}};
        originalOption = {xAxis: {},yAxis: {}};
        amplitudeChart.setOption(amplitudeOption);
        displacementChart.setOption(displacementOption);
        originalChart.setOption(originalOption);
    }
    //刷新
    function refresh(moIds) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_latest_rec/select/v1.0",
            type: "post",
            data: {
                moIds: moIds
            },
            dataType: "json",
            beforeSend: function () {
                clearInterval(timer);
            },
            success: function (result) {
                // console.log("refresh: id="+moIds);
                if (result.stateCode == 0) {
                    if (result.data != null) { //list有值
                        bindAllDatas(result);
                    }
                    // else {
                    //     myChart.showLoading({text: "无数据"})
                    // }
                } else {
                    console.log(result.stateMsg);
                }
            },
            complete: function () {
                timer = setInterval(function () {
                    refresh(moIds);
                }, config.motorInter);
            }
        });
    }
    //数据处理
    function bindDataTop(result) {
        var listArr = [];
        var objDisplacement = {
            moId: [],
            moName: [],
            strRecTime: [],
            multiArr: []
        };
        var objOriginal = {
            moId: [],
            moName: [],
            strRecTime: [],
            multiArr: []
        };
        for (var k in result.data) {
            listArr.push({mId: k, lastData: result.data[k]});
        }
            var valDisplacement = [] , valOriginal = [];
            var datak = [];
            for (var k in result.data) {
                if(result.data[k].length >0){
                    datak = result.data[k];
                    objDisplacement.moId.push(k);
                    objOriginal.moId.push(k);
                    if(datak[0].moName == null){
                        objDisplacement.moName.push('');
                        objOriginal.moName.push('');
                    }else{
                        objDisplacement.moName.push(datak[0].moName);
                        objOriginal.moName.push(datak[0].moName);
                    }
                    valDisplacement = [];
                    valOriginal = [];
                    if(datak != null){
                        for (var i = 0; i < datak.length; i++) {
                            valDisplacement.push(datak[i].displacementData);
                            valOriginal.push(datak[i].rockData);
                        }
                        objDisplacement.multiArr.push({name: datak[0].moName, value: valDisplacement});
                        objOriginal.multiArr.push({name: datak[0].moName, value: valOriginal});
                    }
                }
            }
            for(var i = 0; i < datak.length; i++){
                if(datak.length != 0){
                    if(datak[i].strRecTime != null){
                        objDisplacement.strRecTime.push(datak[i].strRecTime);
                        objOriginal.strRecTime.push(datak[i].strRecTime);
                    }else{
                        objDisplacement.strRecTime.push('');
                        objOriginal.strRecTime.push('');
                    }
                }
            }
        DisplacementStepLine(objDisplacement);
        originalLineChart(objOriginal);

    }
    function bindDataAmplitude(result) {
        var listArr = [];
        var objAmplitude = {
            counts: 1,  //马达个数， 1为单个，0为多个
            moId: [],
            moName: [],
            ctype: ctype,
            strRecTime: [],
            singleObj: {
                shockData: [],
                upperLimit: [],
                lowerLimit: [],
                upperLimitInner: [],
                lowerLimitInner: []
            },
            multiArr: []
        };
        for (var k in result.data) {
            if(result.data[k] != null && result.data[k].length >0){
                listArr.push({mId: k, lastData: result.data[k]});
            }
        }
        if(listArr.length == 0){
            blankChart();
        }else if (listArr.length == 1) { //单个马达，显示上下限及管制上下限，显示motorInfo表格
            var single = listArr[0];
            if(single.lastData != null && single.lastData.length>0){
                objAmplitude.counts = 1;
                objAmplitude.ctype = ctype;
                objAmplitude.legend = [];
                objAmplitude.moId.push(single.mId);
                objAmplitude.moName.push(single.lastData[0].moName);
                var rectime = "";
                for (var i = 0; i < single.lastData.length; i++) {
                    objAmplitude.strRecTime.push(single.lastData[i].strRecTime);
                    objAmplitude.singleObj.shockData.push(single.lastData[i].shockData); //振幅
                    objAmplitude.singleObj.upperLimit.push(single.lastData[i].upperLimit == -1 ? null : single.lastData[i].upperLimit); //上限
                    objAmplitude.singleObj.lowerLimit.push(single.lastData[i].lowerLimit == -1 ? null : single.lastData[i].lowerLimit); //下限
                    objAmplitude.singleObj.upperLimitInner.push(single.lastData[i].upperLimitInner == -1 ? null : single.lastData[i].upperLimitInner); //管制上限
                    objAmplitude.singleObj.lowerLimitInner.push(single.lastData[i].lowerLimitInner == -1 ? null : single.lastData[i].lowerLimitInner); //管制下限
                }
                AmplitudeStepLine(objAmplitude);
            }

        } else {  //多个马达只显示多条振幅折线，不显示表格及上下限
            objAmplitude.counts = 0;
            objAmplitude.ctype = ctype;
            var val = [];
            var datak = [];
            var timeArr = [];
            for (var k in result.data) {
                objAmplitude.moId.push(k);
                datak = result.data[k];
                if(datak != null && datak.length > 0){
                    var xname = "";
                    xname = datak[0].moName != null ? datak[0].moName: "";
                    objAmplitude.moName.push(xname);
                    val = [];
                    for (var i = 0; i < datak.length; i++) {
                        val.push(datak[i].shockData);
                        timeArr.push(datak[i].strRecTime);
                    }
                    objAmplitude.multiArr.push({name: xname, value: val});
                }
            }
            var rectime = uniqueArr(timeArr);
            objAmplitude.strRecTime = rectime.length === 60 ? rectime : rectime.slice(0,60);
            AmplitudeStepLine(objAmplitude);
        }
    }
    //位移step line
    function DisplacementStepLine(obj){
        var optionSeries = [];
        for (var i = 0; i < obj.multiArr.length; i++) {
            optionSeries.push({
                //实时数据
                name: obj.multiArr[i].name,
                type: 'line',
                step: 'middle',
                symbol: 'none',
                data: obj.multiArr[i].value
            });
        }
        var element = {
            title: '位移实时图',
            unit: 'mm',
            max: 2,
            isShowLegend: false,
            isShowAxisLabel: false
        };
        displacementOption = initOptions(obj,element,optionSeries);
        displacementChart.setOption(displacementOption);
    }

    //showLoading
    function isShowLoading(x){
        if(x == 1){ // 1显示
            amplitudeChart.showLoading();
            displacementChart.showLoading();
            originalChart.showLoading();
        }else if(x == 0){ // 0隐藏
            amplitudeChart.hideLoading();
            displacementChart.hideLoading();
            originalChart.hideLoading();
        }
    }
    //清除echarts
    function clearEc(){
        amplitudeChart.clear();
        displacementChart.clear();
        originalChart.clear();
    }
    //调用数据处理
    function bindAllDatas(result){
        bindDataAmplitude(result); //右下振幅
        bindDataTop(result); //右上位移+大数据
        bindRockDataTable(result.data); //左表格
    }
    /*公共option
    * obj:数据对象
    * element: 基础参数：title、unit、max、isShowLegend、isShowAxisLabel
    * optionSeries: 系列值
    * */
    function initOptions(obj,element,optionSeries){
        return {
            backgroundColor: 'transparent',
            color: colors,
            title: {
                text: element.title,
                x:'10%',
                y: 'top',
                textStyle: {
                    color: '#fff',
                    border: 1,
                    fontSize: 16
                }
            },
            // color: color,
            tooltip: {trigger: 'axis'},
            grid: {containLabel: true},
            legend: {
                show: element.isShowLegend,
                x: 'right',
                data: []
            },
            xAxis: {
                name: '',
                type: 'category',
                boundaryGap: false,
                data: obj.strRecTime,
                axisLabel:{
                    show: element.isShowAxisLabel,
                    rotate: -20,
                    formatter:function(val){
                        var hms = val == "" ? "" : val.split(" ")[1];
                        return hms
                    }
                },
                axisTick: {show: false}
            },
            yAxis: {
                type: 'value',
                name: element.unit,
                max: element.max
            },
            series: optionSeries

        };
    }

    // 指定排序的比较函数
    function initSort(property,type) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if(type == 'desc'){
                return value2 - value1;
            }else if(type == 'asc'){
                return value1 - value2;
            }

        }
    }

    //ES6 set结构做数组去重
    function uniqueArr(arr){
        var x = new Set(arr);
        return [...x];
    }

    //阻止冒泡
    function stopBubble(e) {
        if (e && e.stopPropagation) {
            //非IE浏览器
            e.stopPropagation();
        } else {
            //IE
            window.event.cancelBubble = true;
        }
    }

});